use std::{collections::HashMap, u32};

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

pub fn str_to_json(content: &str) {
    //    let json_co:HashMap<String, String> = serde_json::from_str(content).unwrap();

    //     println!("个人信息：{:?}",json_co);
    //   let json_data = serde_json::json!({
    //       "name":"addd",
    //       "age":12
    //   });

    //  println!("打印输出： {:?}",json_data);
    //  json_data.to_string();
    let persion = Persion::new();
    let _ = serde_json::to_value(persion);

    match serde_json::from_str::<Value>(content) {
        Ok(json_value) => {
            println!("解析json数据： {:?}", json_value);
            let mut persion = Persion::new();

            let val = &json_value["name"];
            if !val.is_null() {
                if let Some(name) = val.as_str() {
                    persion.name = name.to_string();
                };
            }

            let val = &json_value["age"];
            if !val.is_null() {
                if let Some(age) = val.as_u64() {
                    persion.age = age;
                };
            }

            // println!("打印persion: {:?}", persion)
        }
        Err(e) => {
            println!("匹配失败： {:?}", e)
        }
    };

    test_obj_json();
    test_json_obj();
}

/**
 * 测试 object 转 json
 * */
pub fn test_obj_json() {
    let persion = Persion::new();

    let json_str = serde_json::to_value(persion).unwrap().to_string();

    println!("打印 test_obj_json： {:?}", json_str)
}

pub fn test_json_obj() {
    let json_str = r#"{
    "name":"lisi",
    "age":12,
    "data":null
  }"#;

    let persion: Persion = serde_json::from_str(&json_str).unwrap();
    println!("打印数据 test_json_obj： {:?}", persion)

}



#[derive(Debug, Clone, Serialize, Deserialize)]
struct Persion {
    name: String,
    #[serde(default)]
    age: u64,
    #[serde(default)]
    data: Value,
}

impl Persion {
    fn new() -> Persion {
        Persion {
            name: String::from("张三"),
            age: 12,
            data: Value::Null,
        }
    }
}
